# -*- coding: utf-8 -*-
from numpy import *

turnDescFmt = 'Step[%d]-%s--[%s]:'
gameOverFmt1 = '-*- Game Finished!-*-\n-*-Winner is %s-*-'
gameOverFmt2 = '-*- Game Finished!-*-\n-*- Draw!!! -*-'
PlayerSign = 'O'
ComputerSign = 'X'


# simple = [None] * 9


class TZ(object):
    def __init__(self):
        super(TZ, self).__init__()
        self.board = None
        self.game = None
        self.gameData = None
        self.playerSteps = []
        self.aiSteps = []
        self.stepNum = 0
        self.whoTurn = None
        self.VocLst = None
        self.availableVocLst = []
        self.aiFn = 'db/ai.db'
        self.simpleFn = 'db/simples.bin'

    def showBoard(self):
        import utils
        print 'board like:'
        utils.console(self.board)
        print 'your sign -- %s\ncomputer sign -- %s' % (PlayerSign, ComputerSign)

    def newGame(self):
        self.selfTrain()
        import gameKits
        self.game = gameKits.newGame()
        self.playerSteps = []
        self.aiSteps = []
        self.stepNum = 1
        self.VocLst = gameKits.VocLst
        self.availableVocLst.extend(gameKits.stepLst[:-1])

    @staticmethod
    def whoFirst(player=None, stagyType=0):
        if stagyType == 0:
            if int(random.uniform(0, 10)) >= 5:
                return 1
            else:
                return 0
        else:
            if player:
                return 1
            else:
                return 0

    def showGameStage(self, step):
        import utils
        print turnDescFmt % (self.stepNum, self.whoTurn, step)
        utils.console(self.game)

    def playStep(self, step=None):
        import gameKits
        if step is None:
            step = raw_input('your step[A1-C3]?:').upper()
        step = gameKits.checkStepIlligal(step, self.availableVocLst)
        self.availableVocLst.remove(step)
        self.whoTurn = 'Player'
        self.game[step] = PlayerSign
        self.playerSteps.append(step)
        self.showGameStage(step)

    def aiStep(self):
        import AI
        import gameKits
        filledAiSteps = gameKits.trans2OppSteps(self.aiSteps)
        filledAiSteps = gameKits.fillSteps(filledAiSteps)
        filledPlayerSteps = gameKits.trans2OppSteps(self.playerSteps)
        filledPlayerSteps = gameKits.fillSteps(filledPlayerSteps)
        aiSets = []
        for voc in self.availableVocLst:
            aiSteps = []
            aiSteps.extend(self.aiSteps)
            aiSteps.append(voc)
            aiSteps = gameKits.trans2SelfSteps(aiSteps)
            aiSteps = gameKits.fillSteps(aiSteps)
            aiSteps.extend(filledPlayerSteps)
            aiSteps.append(voc)
            aiSets.append(aiSteps)
        playerSets = []
        for voc in self.availableVocLst:
            pSteps = []
            pSteps.extend(self.playerSteps)
            pSteps.append(voc)
            pSteps = gameKits.trans2SelfSteps(pSteps)
            pSteps = gameKits.fillSteps(pSteps)
            pSteps.extend(filledAiSteps)
            pSteps.append(voc)
            playerSets.append(pSteps)
        step = AI.Decision(aiSets, playerSets, self.availableVocLst, self.VocLst, self.aiFn)
        self.availableVocLst.remove(step)
        self.whoTurn = 'AI'
        self.game[step] = ComputerSign
        self.aiSteps.append(step)
        self.showGameStage(step)

    def exportSimple(self, winFlag):
        import gameKits
        f = open(self.simpleFn, 'a')
        pre_half_simple = gameKits.trans2SelfSteps(self.playerSteps)
        pre_half_simple = gameKits.fillSteps(pre_half_simple)
        suff_half_simple = gameKits.trans2OppSteps(self.aiSteps)
        suff_half_simple = gameKits.fillSteps(suff_half_simple)
        simple = pre_half_simple
        simple.extend(suff_half_simple)
        simple.append(str(winFlag))
        ln = '\t'.join(simple)
        ln += '\n'
        f.write(ln)
        f.close()

    def nextStep(self):
        import gameKits
        isOver, WinnerSign = gameKits.isGameOver(gameKits.game2gameData(self.game))
        while isOver != 1:
            if self.whoTurn == 'AI':
                self.playStep()
            else:
                self.aiStep()
            isOver, WinnerSign = gameKits.isGameOver(gameKits.game2gameData(self.game))
        if WinnerSign == PlayerSign:
            self.exportSimple(1)
            print gameOverFmt1 % 'Player'
        elif WinnerSign == ComputerSign:
            self.exportSimple(-1)
            print gameOverFmt1 % 'Computer'
        else:
            self.exportSimple(0)
            print gameOverFmt2

    def playNewGame(self):
        import gameKits
        self.newGame()
        self.board = gameKits.Board
        self.showBoard()
        if self.whoFirst():
            step = raw_input('you first[A1-C3]:').upper()
            self.playStep(step)
        else:
            print('computer first')
            self.aiStep()
        self.nextStep()

    def selfTrain(self):
        import gameKits
        import AI
        f = open(self.simpleFn, 'r')
        lns = f.readlines()
        f.close()
        if lns is None or len(lns) == 0:
            return
        routeSimples = [ln.replace('\n', '') for ln in lns]
        # routeSimples = set(routeSimples)
        simples = [ln.split('\t')[:-1] for ln in routeSimples]
        cata = [int(ln.split('\t')[-1]) for ln in routeSimples]
        VectArry, pClassArr = AI.trainNB([AI.set2Vec(gameKits.VocLst, simple) for simple in simples], cata)
        # print simples
        # print cata
        # print [AI.set2Vec(gameKits.VocLst, simple) for simple in simples]
        # print VectArry, pClassArr
        AI.storeTrainRst([VectArry, pClassArr], self.aiFn)


tz = TZ()
tz.playNewGame()
